package services

import (
	"gitee.com/zhoulvvv/my_go_gateway/dao"
	"gitee.com/zhoulvvv/my_go_gateway/dto"
	"gitee.com/zhoulvvv/my_go_gateway/public"
	"github.com/e421083458/golang_common/lib"
	"github.com/gin-gonic/gin"
	"github.com/pkg/errors"
	"gorm.io/gorm"
	"log"
	"time"
)

type DashBoardService struct {
	tx *gorm.DB
}

func NewDashBoardService() (*DashBoardService, error) {
	tx, err := lib.GetGormPool("default")
	if err != nil {
		return nil, errors.New("获取数据库连接池失败")
	}
	return &DashBoardService{tx: tx}, nil
}

// 获取首页大盘指标
func (d *DashBoardService) PanelGroupData(ctx *gin.Context) (*dto.PanelGroupDataListOutput, error) {
	serviceInfoService, err := NewServiceServices()
	if err != nil {
		return nil, errors.New("创建ServiceServices对象失败：" + err.Error())
	}
	// 查询服务信息
	serviceServicesOutputModel, err := serviceInfoService.GetPageList(ctx, &dto.ServiceListInput{PageNo: 1, PageSize: 1})
	if err != nil {
		return nil, errors.New("统计服务信息失败：" + err.Error())
	}

	appService, err := NewAppService()
	if err != nil {
		return nil, errors.New("创建AppService对象失败：" + err.Error())
	}
	// 查询租户信息
	appServicesOutput, err := appService.GetAppList(ctx, &dto.AppListInput{
		PageNo:   1,
		PageSize: 1,
	})
	if err != nil {
		return nil, errors.New("统计租户信息失败：" + err.Error())
	}
	counter, err := public.FlowCounterHandler.GetCounter(public.FlowTotal)
	if err != nil {
		return nil, errors.New("指标统计获取全局QPS计数器失败：" + err.Error())
	}
	return &dto.PanelGroupDataListOutput{
		ServiceNum:      int64(serviceServicesOutputModel.Total),
		AppNum:          appServicesOutput.Total,
		CurrentQPS:      counter.QPS,
		TodayRequestNum: counter.TotalCount,
	}, nil
}

func (d *DashBoardService) FlowStat(ctx *gin.Context) (*dto.PanelStatOutput, error) {
	counter, err := public.FlowCounterHandler.GetCounter(public.FlowTotal)
	if err != nil {
		return nil, errors.New("获取QPS计数器失败：" + err.Error())
	}
	todayList := []int64{}
	currentTime := time.Now()
	// time.Now().Hour() 获取当前小时
	for i := 0; i <= currentTime.Hour(); i++ {
		todayHourTime := time.Date(currentTime.Year(), currentTime.Month(), currentTime.Day(), i, 0, 0, 0, lib.TimeLocation)
		todayHourQPS, err := counter.GetHourData(todayHourTime)
		if err != nil {
			log.Printf("获取全站当天 %s 小时的QPS数据出现错误：%s\n", todayHourTime.Format("2006010215"), err.Error())
		}
		todayList = append(todayList, todayHourQPS)
	}

	// 拿取昨天的流量统计
	yesterdayList := []int64{}
	// 获取昨天的时间
	yesterTime := currentTime.Add(-1 * time.Duration(time.Hour*24))
	for i := 0; i <= 23; i++ {
		yesterHourTime := time.Date(yesterTime.Year(), yesterTime.Month(), yesterTime.Day(), i, 0, 0, 0, lib.TimeLocation)
		// 获取当前小时的QPS
		yesterHourQPS, err := counter.GetHourData(yesterHourTime)
		if err != nil {
			log.Printf("获取全站昨天 %s 小时的QPS数据出现错误：%s\n", yesterHourTime.Format("2006010215"), err.Error())
		}
		yesterdayList = append(yesterdayList, yesterHourQPS)
	}

	return &dto.PanelStatOutput{
		Today:     todayList,
		Yesterday: yesterdayList,
	}, nil
}

func (d *DashBoardService) ServiceStat(ctx *gin.Context) (*dto.PanelServiceStatOutput, error) {
	serviceInfo := &dao.ServiceInfo{}
	serviceItemOutput, err := serviceInfo.GroupByLoadType(ctx, d.tx)
	if err != nil {
		return nil, errors.New("查询服务类型数量失败：" + err.Error())
	}
	legend := []string{}
	for index, item := range serviceItemOutput {
		name, ok := public.LoadTypeMap[item.LoadType]
		if !ok {
			return nil, errors.New("(服务类型不存在)load_type not found")
		}
		legend = append(legend, name)
		serviceItemOutput[index].Name = name
	}
	return &dto.PanelServiceStatOutput{
		Legend: legend,
		Data:   serviceItemOutput,
	}, nil
}
